{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 交管助手"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 一、[车牌识别](https://ai.baidu.com/tech/ocr_cars/plate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24.5eadce34b7d7e8bb9be843d0842a9f46.2592000.1597667462.282335-21461765\n"
     ]
    }
   ],
   "source": [
    " import requests \n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    " host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=GEk0idAgaPRZYxddwHrPsCO1&client_secret=jaPoqqEwQCoG8KIjmjx7oIdpm1H8ezs3'\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json()['access_token'])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': {'number': '陕AE0888', 'vertexes_location': [{'x': 227, 'y': 253}, {'x': 306, 'y': 252}, {'x': 306, 'y': 274}, {'x': 227, 'y': 275}], 'color': 'blue', 'probability': [0.901494026184082, 0.9013763070106506, 0.9015293121337891, 0.9007359743118286, 0.901617705821991, 0.9013881683349609, 0.9010502099990845]}, 'log_id': 1284467319933763584}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'words_result': {'number': '陕AE0888',\n",
       "  'vertexes_location': [{'x': 227, 'y': 253},\n",
       "   {'x': 306, 'y': 252},\n",
       "   {'x': 306, 'y': 274},\n",
       "   {'x': 227, 'y': 275}],\n",
       "  'color': 'blue',\n",
       "  'probability': [0.901494026184082,\n",
       "   0.9013763070106506,\n",
       "   0.9015293121337891,\n",
       "   0.9007359743118286,\n",
       "   0.901617705821991,\n",
       "   0.9013881683349609,\n",
       "   0.9010502099990845]},\n",
       " 'log_id': 1284467319933763584}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "import base64\n",
    "'''\n",
    "OCR 通用识别\n",
    "'''\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('D:\\car.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '[24.5eadce34b7d7e8bb9be843d0842a9f46.2592000.1597667462.282335-21461765]'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())\n",
    "results = response.json()\n",
    "results\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 二、位置识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'status': '1', 'info': 'OK', 'infocode': '10000', 'count': '1', 'geocodes': [{'formatted_address': '广东省广州市从化区中山大学南方学院', 'country': '中国', 'province': '广东省', 'citycode': '020', 'city': '广州市', 'district': '从化区', 'township': [], 'neighborhood': {'name': [], 'type': []}, 'building': {'name': [], 'type': []}, 'adcode': '440117', 'street': [], 'number': [], 'location': '113.679287,23.632575', 'level': '兴趣点'}]}\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>formatted_address</th>\n",
       "      <th>country</th>\n",
       "      <th>province</th>\n",
       "      <th>citycode</th>\n",
       "      <th>city</th>\n",
       "      <th>district</th>\n",
       "      <th>township</th>\n",
       "      <th>adcode</th>\n",
       "      <th>street</th>\n",
       "      <th>number</th>\n",
       "      <th>location</th>\n",
       "      <th>level</th>\n",
       "      <th>neighborhood.name</th>\n",
       "      <th>neighborhood.type</th>\n",
       "      <th>building.name</th>\n",
       "      <th>building.type</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>广东省广州市从化区中山大学南方学院</td>\n",
       "      <td>中国</td>\n",
       "      <td>广东省</td>\n",
       "      <td>020</td>\n",
       "      <td>广州市</td>\n",
       "      <td>从化区</td>\n",
       "      <td>[]</td>\n",
       "      <td>440117</td>\n",
       "      <td>[]</td>\n",
       "      <td>[]</td>\n",
       "      <td>113.679287,23.632575</td>\n",
       "      <td>兴趣点</td>\n",
       "      <td>[]</td>\n",
       "      <td>[]</td>\n",
       "      <td>[]</td>\n",
       "      <td>[]</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   formatted_address country province citycode city district township  adcode  \\\n",
       "0  广东省广州市从化区中山大学南方学院      中国      广东省      020  广州市      从化区       []  440117   \n",
       "\n",
       "  street number              location level neighborhood.name  \\\n",
       "0     []     []  113.679287,23.632575   兴趣点                []   \n",
       "\n",
       "  neighborhood.type building.name building.type  \n",
       "0                []            []            []  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "中大南方地理编码: 113.679287,23.632575\n"
     ]
    }
   ],
   "source": [
    "获取地理位置编码\n",
    "import pandas as pd\n",
    "import requests\n",
    "key_miao =\"83f8ce2754ee0e0940928a32b46e79ee\"\n",
    "def geocode(address,city=None,batch=None,sig=None)->dict:\n",
    "    \"\"\"获取地理编码\"\"\"\n",
    "    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'\n",
    "    params={\n",
    "        'key': key_miao,\n",
    "        'address':address,\n",
    "        'city':city,\n",
    "        'batch':batch,\n",
    "        'sig':sig,\n",
    "        'output':'json'\n",
    "    }\n",
    "    response = requests.get(url,params=params)\n",
    "    data = response.json()\n",
    "    return data\n",
    "中大南方 = geocode(address='广东省广州市从化区中山大学南方学院')\n",
    "print(中大南方)\n",
    "df_中大南方地理编码 = pd.json_normalize(中大南方['geocodes'])\n",
    "display(df_中大南方地理编码)\n",
    "中大南方地理编码 = 中大南方['geocodes'][0]['location']\n",
    "print(\"中大南方地理编码:\",中大南方地理编码)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 三、文字转语音"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "file saved as : 赵容的罚单信息.mp3\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "\n",
    "# 保证兼容python2以及python3\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "# 替换你的 API_KEY\n",
    "API_KEY = 'nu9r2plGFi3s1ugayDPSM6Mk'\n",
    "\n",
    "# 替换你的 SECRET_KEY\n",
    "SECRET_KEY = 'G62YGnq84eKTqu0mBgvdpmC6gNBzHdai'\n",
    "\n",
    "# 罚单信息内容文本\n",
    "TEXT = \"尊敬的赵容先生，您的车辆陕AE0888在北京市顺义区二经路与二纬路交汇处北侧金隅店违规停车，现已扣2分，请尽快开走，多谢您的配合\"\n",
    "\n",
    "\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "\"\"\"\n",
    "    获取token\n",
    "\"\"\"\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "\n",
    "    result = json.loads(result_str)\n",
    "\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not 'audio_tts_post' in result['scope'].split(' '):\n",
    "            print ('please ensure has check the tts ability')\n",
    "            exit()\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        print ('please overwrite the correct API_KEY and SECRET_KEY')\n",
    "        exit()\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "\n",
    "    token = fetch_token()\n",
    "\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "\n",
    "    params = {'tok': token, 'tex': tex, 'cuid': \"quickstart\",\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else u'赵容的罚单信息.mp3'\n",
    "\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"file saved as : \" + save_file)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
